<?php
namespace app\admin\controller;
use app\common\controller\Admin;

class News extends Admin {

    public function _initialize() {
		parent::_initialize();
		$this->model = model('News');
	}

    public function index()
    {
        $map = array();

		$order = "id desc";
		$list  = $this->model->where($map)->order($order)->paginate(10);

		$data = array(
			'list' => $list,
			'page' => $list->render(),
		);
		$this->assign($data);
		$this->setMeta("科普新闻");
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
			$data = $this->request->post();
            if ($data) {
				$id = $this->model->validate(true)->save($data);
				if ($id) {
					//记录行为
					action_log('add', 'news', $id, session('user_auth.uid'));
					return $this->success('新增成功', url('index'));
				} else {
					return $this->error($this->model->getError());
				}
			} else {
				return $this->error($this->model->getError());
			}
		}else{
            $data = array(
				'keyList' => $this->model->keyList,
			);
			$this->assign($data);
            $this->setMeta("添加新闻");
            return $this->fetch('public/edit');
        }
    }
    //修改
	public function edit() {
		$id   = input('id', '', 'trim,intval');
		if ($this->request->isPost()) {
			$data = input('post.');
			if ($data) {
				$result = $this->model->validate(true)->save($data, array('id' => $id));
				if ($result) {
					return $this->success("修改成功！", url('News/index'));
				} else {
					return $this->error($this->model->getError());
				}
			} else {
				return $this->error($this->model->getError());
			}
		} else {
            $info = $this->model->where(array('id' => $id))->find();
			if (!$info) {
				return $this->error("非法操作！");
			}
            $data = array(
                'info'    => $info,
				'keyList' => $this->model->keyList,
			);
			$this->assign($data);
			$this->setMeta("编辑新闻");
			return $this->fetch('public/edit');
		}
	}
    //删除
	public function delete() {
		$id = input('id');
		if (empty($id)) {
			return $this->error('非法操作！');
		}
		$map    = array('id' => array('IN', $id));
		$result = $this->model->where($map)->delete();
		if ($result) {
			return $this->success("删除成功！");
		} else {
			return $this->error("删除失败！");
		}
	}
}
